package com.easysettle

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.easysettle.databinding.ActivityMainBinding
import com.easysettle.service.MainService
import java.io.File

/**
 * 主Activity类
 * 作为应用的主入口和功能导航中心
 */
class MainActivity : AppCompatActivity() {
    // ViewBinding实例
    private lateinit var binding: ActivityMainBinding
    // 主服务实例
    private lateinit var mainService: MainService
    
    companion object {
        // 日志标签
        private const val TAG = "MainActivity"
        // 权限请求码
        private const val PERMISSION_REQUEST_CODE = 100
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 初始化ViewBinding
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        // 初始化主服务
        mainService = MainService(this)
        
        // 设置按钮点击监听器
        setupButtonListeners()
        
        // 检查并请求必要的权限
        checkAndRequestPermissions()
        
        // 确保数据目录存在
        ensureDataDirectoryExists()
    }

    /**
     * 设置按钮点击监听器
     */
    private fun setupButtonListeners() {
        // 商品录入按钮
        binding.btnAddProduct.setOnClickListener {
            startActivity(Intent(this, AddProductActivity::class.java))
        }
        
        // 商品管理按钮
        binding.btnManageProducts.setOnClickListener {
            startActivity(Intent(this, ProductManagementActivity::class.java))
        }
        
        // 扫描与结算按钮
        binding.btnScanAndCart.setOnClickListener {
            startActivity(Intent(this, ScanAndCartActivity::class.java))
        }
        
        // 收据打印按钮
        binding.btnReceipt.setOnClickListener {
            startActivity(Intent(this, ReceiptActivity::class.java))
        }
    }

    /**
     * 检查并请求必要的权限
     */
    private fun checkAndRequestPermissions() {
        val permissions = mutableListOf<String>()
        
        // 检查相机权限
        if (!mainService.hasPermission(android.Manifest.permission.CAMERA)) {
            permissions.add(android.Manifest.permission.CAMERA)
        }
        
        // 检查存储权限
        if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.TIRAMISU) {
            if (!mainService.hasPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
                permissions.add(android.Manifest.permission.READ_EXTERNAL_STORAGE)
            }
            if (!mainService.hasPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissions.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
            }
        } else {
            if (!mainService.hasPermission(android.Manifest.permission.READ_MEDIA_IMAGES)) {
                permissions.add(android.Manifest.permission.READ_MEDIA_IMAGES)
            }
        }
        
        // 请求权限
        if (permissions.isNotEmpty()) {
            ActivityCompat.requestPermissions(
                this,
                permissions.toTypedArray(),
                PERMISSION_REQUEST_CODE
            )
        }
    }

    /**
     * 确保数据目录存在
     */
    private fun ensureDataDirectoryExists() {
        try {
            val filesDir = filesDir
            if (!filesDir.exists()) {
                filesDir.mkdirs()
                Log.d(TAG, "数据目录已创建")
            }
        } catch (e: Exception) {
            Log.e(TAG, "创建数据目录失败", e)
            Toast.makeText(this, "初始化数据目录失败", Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 处理权限请求结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        if (requestCode == PERMISSION_REQUEST_CODE) {
            val deniedPermissions = mutableListOf<String>()
            
            for (i in permissions.indices) {
                if (grantResults[i] != android.content.pm.PackageManager.PERMISSION_GRANTED) {
                    deniedPermissions.add(permissions[i])
                }
            }
            
            if (deniedPermissions.isNotEmpty()) {
                Log.w(TAG, "以下权限被拒绝: $deniedPermissions")
                Toast.makeText(
                    this,
                    "某些功能可能无法正常使用，请在设置中授予权限",
                    Toast.LENGTH_LONG
                ).show()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        // 清理主服务资源
        mainService.cleanup()
    }
}